package com.alog.yzd.bookmall.web.servlet.user;

import com.alog.yzd.bookmall.domain.user.User;
import com.alog.yzd.bookmall.exception.UserException;
import com.alog.yzd.bookmall.service.user.UserService;
import com.alog.yzd.commons.CommonUtils;
import com.alog.yzd.commons.Print;
import com.alog.yzd.commons.servlet.BaseServlet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户模块的控制层
 */
public class UserServlet extends BaseServlet {
    private UserService userService = new UserService();

    /**
     * 退出登陆
     * @return
     * @throws IOException
     */
    public String quit(HttpServletRequest request, HttpServletResponse response) throws IOException{
        request.getSession().removeAttribute("sessionUser");
        return "r:/jsps/user/login.jsp";
    }
    /**
     * 修改密码
     * @return
     * @throws IOException
     */
    public String updatePassword(HttpServletRequest request, HttpServletResponse response) throws IOException{
        Print.print("updatePassword");
        User user = CommonUtils.toBean(request.getParameterMap(), User.class);
        User sessionUser = (User) request.getSession().getAttribute("sessionUser");
        if(sessionUser == null){
            request.setAttribute("msg", "您还没有登陆");
            return "f:/jsps/user/login.jsp";
        }
        try {
            userService.updatePassword(sessionUser.getUid(), user.getLoginpass(), user.getReloginpass());
            request.setAttribute("msg", "修改密码成功");
            request.setAttribute("code", "sucess");
            return "f:/jsps/msg.jsp";
        } catch (UserException e) {
            request.setAttribute("msg", e.getMessage());
            request.setAttribute("user", user);
            return "f:/jsps/user/pwd.jsp";
        }
    }

    /**
     * 登陆
     * @return
     * @throws IOException
     */
    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException{
        Print.print("login");
        User user = CommonUtils.toBean(request.getParameterMap(), User.class);
        Map<String, String> errors = validateLogin(user, request.getSession());
        if(errors.size() > 0){
            request.setAttribute("errors", errors);
            request.setAttribute("form", user);
            return "f:/jsps/user/login.jsp";
        }

        User loginUser = userService.login(user);
        Print.print(loginUser);
        if(loginUser == null){
            request.setAttribute("msg", "用户名或密码错误");
            request.setAttribute("user", user);
            return "f:/jsps/user/login.jsp";
        } else {
            if(!loginUser.isStatus()){
                request.setAttribute("msg", "您还没有激活");
                request.setAttribute("user", user);
                return "f:/jsps/user/login.jsp";
            } else {
                request.getSession().setAttribute("sessionUser", loginUser);

                String loginname = URLEncoder.encode(loginUser.getLoginname(), "utf-8");
                Cookie cookie = new Cookie("loginname", loginname);
                cookie.setMaxAge(60 * 60 * 24 * 10);
                response.addCookie(cookie);
                return "r:/index.jsp";
            }
        }

    }


    /**
     * 激活
     * @return
     * @throws IOException
     */
    public String activation(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String activationCode = request.getParameter("activationCode");
        Print.print("activation");
        try {
            userService.activation(activationCode);
            request.setAttribute("code","success");
            request.setAttribute("msg","恭喜,激活成功");
        } catch (UserException e) {
            e.printStackTrace();
            request.setAttribute("code","error");
            request.setAttribute("msg",e.getMessage());
        }
        return "f:/jsps/msg.jsp";
    }
    /**
     * 校验用户名是否已经存在
     * @return
     */
    public String ajaxValidateLoginname(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Print.print("ajaxValidateLoginname");
        String loginname = request.getParameter("loginname");
        boolean result = userService.ajaxValidateLoginname(loginname);
        response.getWriter().print(result);
        return null;
    }
    /**
     * 校验邮箱是否已经存在
     * @return
     */
    public String ajaxValidateEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Print.print("ajaxValidateEmail");
        String email = request.getParameter("email");
        boolean result = userService.ajaxValidateEmail(email);
        response.getWriter().print(result);
        return null;
    }

    /**
     * 校验邮箱是否已经存在
     * @return
     */
    public String ajaxValidateVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Print.print("ajaxValidateVerifyCode");
        String code = request.getParameter("verifyCode");
        String vCode = (String)request.getSession().getAttribute("vCode");
        boolean result = code.equalsIgnoreCase(vCode);
        response.getWriter().print(result);
        return null;
    }

    /**
     * 注册校验
     * @param user
     * @return
     */
    private Map<String, String> validateRegist(User user, HttpSession session){
        Map<String, String> errors = new HashMap<>();

        String loginname = user.getLoginname();
        if(loginname == null || loginname.trim().isEmpty()){
            errors.put("loginname", "用户名不能为空");
        } else if(loginname.length() < 3 || loginname.length() > 20){
            errors.put("loginname", "用户名长度必须在3到20之间");
        } else if(!userService.ajaxValidateLoginname(loginname)){
            errors.put("loginname", "用户名已被注册");
        }

        String loginpass = user.getLoginpass();
        if(loginpass == null || loginpass.trim().isEmpty()){
            errors.put("loginpass", "密码不能为空");
        } else if(loginpass.length() < 3 || loginpass.length() > 20){
            errors.put("loginpass", "密码长度必须在3到20之间");
        }

        String reloginpass = user.getReloginpass();
        if(reloginpass == null || reloginpass.trim().isEmpty()){
            errors.put("reloginpass", "确认密码不能为空");
        } else if(!reloginpass.equals(loginpass)){
            errors.put("reloginpass", "两次输入不一致");
        }

        String email = user.getEmail();
        if(email == null || email.trim().isEmpty()){
            errors.put("email", "邮箱不能为空");
        } else if(!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")){
            errors.put("email", "邮箱格式错误");
        } else if(!userService.ajaxValidateEmail(email)){
            errors.put("email", "邮箱已被注册");
        }

        String verifyCode = user.getVerifyCode();
        if(verifyCode == null || verifyCode.trim().isEmpty()){
            errors.put("verifyCode", "验证码不能为空");
        } else if(!verifyCode.equalsIgnoreCase((String)session.getAttribute("vCode"))){
            errors.put("verifyCode", "验证码错误");
        }
        return errors;
    }

    /**
     * 注册
     * @param request
     * @param response
     * @return
     */
    public String regist(HttpServletRequest request, HttpServletResponse response){
        Print.print("regist");
        User formUser = CommonUtils.toBean(request.getParameterMap(), User.class);
        Map<String, String> errors = validateRegist(formUser, request.getSession());
        if(errors.size() > 0){
            request.setAttribute("errors", errors);
            request.setAttribute("form", formUser);
            return "f:/jsps/user/regist.jsp";
        }

        userService.regist(formUser);
        request.setAttribute("code","success");
        request.setAttribute("msg","注册成功, 请到邮箱激活");
        return "f:/jsps/msg.jsp";
    }

    private Map<String, String> validateLogin(User user, HttpSession session){
        Map<String, String> errors = new HashMap<>();
        String loginname = user.getLoginname();
        if(loginname == null || loginname.trim().isEmpty()){
            errors.put("loginname", "用户名不能为空");
        } else if(loginname.length() < 3 || loginname.length() > 20){
            errors.put("loginname", "用户名长度必须在3到20之间");
        }

        String loginpass = user.getLoginpass();
        if(loginpass == null || loginpass.trim().isEmpty()){
            errors.put("loginpass", "密码不能为空");
        } else if(loginpass.length() < 3 || loginpass.length() > 20){
            errors.put("loginpass", "密码长度必须在3到20之间");
        }

        String verifyCode = user.getVerifyCode();
        if(verifyCode == null || verifyCode.trim().isEmpty()){
            errors.put("verifyCode", "验证码不能为空");
        } else if(!verifyCode.equalsIgnoreCase((String)session.getAttribute("vCode"))){
            errors.put("verifyCode", "验证码错误");
        }
        return errors;
    }
}
